﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace olierFrm.Extensions.Client
{
    public static class IP
    {

        /// <summary>
        ///  通过代理，获取真实的客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetClientIPAddress(this HttpRequestBase request)
        {
            try
            {
                string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (null == result || result == String.Empty)
                {
                    result = request.ServerVariables["REMOTE_ADDR"];
                }

                if (null == result || result == String.Empty)
                {
                    result = request.UserHostAddress;
                }
                return result;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        ///  通过代理，获取真实的客户端IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetClientIPAddress(this HttpRequest request)
        {
            try
            {
                string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (null == result || result == String.Empty)
                {
                    result = request.ServerVariables["REMOTE_ADDR"];
                }

                if (null == result || result == String.Empty)
                {
                    result = request.UserHostAddress;
                }
                return result;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static dynamic GetLocation(this HtmlHelper html, string filePath)
        {
            olierFrm.Extensions.Client.QQwry.QQWryLocator wry = new QQwry.QQWryLocator(filePath);
            var ip = wry.Query(GetClientIPAddress(HttpContext.Current.Request));
            return new { ip.Local, ip.IP, ip.Country };
        }
    }
}
